import com.crowdfunding.activiti.listener.NoListener;
import com.crowdfunding.activiti.listener.YesListener;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestActiviti7 {
    ApplicationContext ioc=new ClassPathXmlApplicationContext("spring/spring-*.xml");
    ProcessEngine processEngine=(ProcessEngine) ioc.getBean("processEngine");
    //部署流程定义
    @Test
    public void test01(){
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Deployment deploy = repositoryService.createDeployment().addClasspathResource("MyProcess9.bpmn").deploy();
        System.out.println("deploy="+deploy);
    }
    //启动流程实例
    @Test
    public void test02(){
        ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery().latestVersion().singleResult();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        Map<String,Object>map=new HashMap<>();
        map.put("yesListener",new YesListener());
        map.put("noListener",new NoListener());
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(),map);
        System.out.println("processInstance="+processInstance);
    }
    //流程监听器
    //flag为true
    @Test
   public void test03(){
        ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery().latestVersion().singleResult();
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery.taskAssignee("zhangsan").list();
        for (Task task : list) {
            taskService.setVariable(task.getId(),"flag","true");
            taskService.complete(task.getId());
        }
    }
    //流程监听器
    //flag为false
    @Test
    public void test04(){
        ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery().latestVersion().singleResult();
        TaskService taskService = processEngine.getTaskService();
        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery.taskAssignee("zhangsan").list();
        for (Task task : list) {
            taskService.setVariable(task.getId(),"flag","false");
            taskService.complete(task.getId());
        }
    }

}
